<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>社区活动</title>
  <meta name="renderer" content="webkit">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <link rel="stylesheet" href="${resRoot}/layui/css/layui.css" media="all" />
  <link rel="stylesheet" href="${resRoot}/layui/admin/admin.css" media="all" />
 <link id="layuicss-layer" rel="stylesheet" href="${resRoot}/layui/css/modules/layer/default/layer.css" media="all">
 <script src="${resRoot}/ckeditor/ckeditor.js"></script>
 <script type="text/javascript">
	    window.onload = function()
	    {
	        CKEDITOR.replace('content');
	    };
	</script>
</head>
<body class="childrenBody" style="height: 100%">
          <div class="layui-fluid">   
          <div class="layui-card">
          <div class="layui-card-body">
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;">
  <legend><#if NoticeDTO??>更新<#else>新增</#if>社区活动</legend>
</fieldset>
 
<form class="layui-form" action="#" >
	<input type="hidden" id="id" value="<#if NoticeDTO??>${NoticeDTO.id}<#else>0</#if>" >
	
  <div class="layui-form-item">
    <label class="layui-form-label">所属类型</label>
    <div class="layui-input-inline">
      <select name="type" id="type" lay-verify="required" >
        <#list communityTypeList as communityType>
        <#if communityType.id==2>
        <option value="${communityType.id}" <#if NoticeDTO?? && communityType.id +''==NoticeDTO.type >selected="selected"</#if> >${communityType.name}</option>
        </#if>
        </#list>
      </select>
    </div>
  </div>
  
  <div class="layui-form-item">
    <label class="layui-form-label">活动状态</label>
    <div class="layui-input-inline">
      <select name="state" id="state" lay-verify="required" >
        <option value=""></option>
        <option <#if NoticeDTO?? && NoticeDTO.type=="0" >selected="selected"</#if> value="0">未开始</option>
        <option <#if NoticeDTO?? && NoticeDTO.type=="1" >selected="selected"</#if> value="1">进行中</option>
        <option <#if NoticeDTO?? && NoticeDTO.type=="2" >selected="selected"</#if> value="2">已结束</option>
      </select>
    </div>
  </div>
  
  <div class="layui-form-item">
    <label class="layui-form-label">标题</label>
    <div class="layui-input-block">
      <input type="text" name="title" id="title" value="<#if NoticeDTO??>${NoticeDTO.title!}</#if>" lay-verify="required" autocomplete="off" placeholder="请输入标题" class="layui-input">
    </div>
    
  </div>
  
  <div class="layui-form-item">
    <label class="layui-form-label">来源</label>
    <div class="layui-input-inline">
      <input type="text" name="source" id="source" value="<#if NoticeDTO??>${NoticeDTO.source}</#if>" lay-verify="required" autocomplete="off" placeholder="请输入来源" class="layui-input">
    </div>
  </div>
  
  <div class="layui-form-item">
    <label class="layui-form-label">阅读数量</label>
    <div class="layui-input-inline">
      <input type="number" id="readCount" value="<#if NoticeDTO??>${NoticeDTO.readCount}</#if>" name="lable" lay-verify="required" placeholder="请输入阅读数量" autocomplete="off" class="layui-input">
    </div>
  </div>
  
  <div class="layui-form-item">
    <label class="layui-form-label">内容</label>
    <div class="layui-input-block">
  <textarea class="layui-textarea" name="content" id="content" ><#if NoticeDTO??>${NoticeDTO.content!}</#if></textarea>
    </div>
  </div>
  
  
  <div class="layui-form-item">
    <div class="layui-inline">
      <label class="layui-form-label">上传图片</label>
      <div class="layui-input-block">
      <div class="site-demo-upload" id="site-demo-upload">
      <#if NoticeDTO?? && NoticeDTO.picUrlList??>
      <#list NoticeDTO.picUrlList as picUrl>
  <img id="LAY_demo_upload_${picUrl_index+1}" name="LAY_demo_upload" src="${picUrl}" onclick="removeThis(id);" style="max-width:200px;max-height:200px;margin-left: 5px;">
      </#list>
  </#if>
  <br/>
  <button type="button" class="layui-btn" id="test">
  <i class="layui-icon"></i>上传图片
</button><input class="layui-upload-file" type="file" accept="images" name="fileField" id="fileField">
</div>
      </div>
    </div>
  </div>
  <input type="hidden" id="picUrl" name="picUrl"> 

  <div class="layui-form-item">
    <div class="layui-input-block">
      <button class="layui-btn" id="submitBtn"  lay-submit=""  type="button">立即提交</button>
      <button type="reset" class="layui-btn layui-btn-primary">重置</button>
      <button type="button" class="layui-btn layui-btn-primary" onclick="history.go(-1);" >返回</button>
    </div>
  </div>
</form>
 </div>
          </div>
          </div>
<script src="${resRoot}/layui/layui.js" charset="utf-8"></script>
<script src="${resRoot}/js/jquery.min.js?v=2.1.4"></script>
<script src="${resRoot}/layui/layui.all.js" charset="utf-8"></script>
<script>
function removeThis(id) {
	layer.confirm('您是确认删除该文件吗？',{
		  btn: ['确认','取消'] //按钮
		}, function(){
			$("#"+id).remove();
			layer.msg('已删除！');
		}, function(){
		  layer.msg('已取消！');
		});
	}
layui.use(['form', 'layedit', 'laydate'], function(){
  var form = layui.form
  ,layer = layui.layer
  ,layedit = layui.layedit
  ,laydate = layui.laydate,
  $ = layui.jquery;
  
  //构建一个默认的编辑器
  layedit.set({
                uploadImage: {
                    url: '${base}/textUploadImage' //接口url
                  , type: 'post' //默认post
                }
            });
var editIndex = layedit.build('LAY_demo1',{
                       height:400
                   }
               );

  
  
  form.on('select(getCommunityTypeList)', function(data){
        
        var villageId=data.value;
		$.ajax({
						type : "post",
						url : "${base}/sys/notice/getCommunityTypeList",
						data : {
							},
						dataType : "json",
						async : false,
						success : function(data) {
							if(data.message != "") {
								var obj = data.message;
								var html = "<option value=''></option>";
								for(var i=0;i<obj.length;i++){
									html = html + "<option value='" + obj[i].id + "'>" + obj[i].name + "</option>";
								}
									$("#type").html(html);
								} else {
								var html = "<option value=''></option>";
								$("#type").html(html);
								}
									layui.use(['form'], function(){
  										var form = layui.form;
  										form.render();
  										});
						}
					}); 
     });  
  
  //自定义验证规则
  form.verify({
    title: function(value){
      if(value.length < 5){
        return '用户名必须不小于5';
      }
    }
    ,pass: [/(.+){6,12}$/, '密码必须6到12位']
    ,content: function(value){
      layedit.sync(editIndex);
    }
  });
  
  $("#submitBtn").click(function(){
		var id = $("#id").val();
				var type =$("#type").val();
				var source =$("#source").val();
				var readCount = $("#readCount").val();
				// var content =layedit.getContent(editIndex);
				var content = CKEDITOR.instances.content.getData();
				var title = $("#title").val();
				var state = $("#state").val();
				var picUrl = "";
				$("img[name='LAY_demo_upload']").each(function(i) {
					picUrl = picUrl + $(this).attr("src") + "#";
				});
				
				var flag = true;
				if(state==""|| state== null || state=="undifined") {
					layer.msg("请选择活动当前状态！");
					flag = false;
					return false;
				}
				if(type==""|| type== null || type=="undifined") {
					layer.msg("请选择类型！");
					flag = false;
					return false;
				}
				if(title==""|| title== null || title=="undifined") {
					layer.msg("请输入标题！");
					flag = false;
					return false;
				}
				if(source==""|| source== null || source=="undifined") {
					layer.msg("请输入来源！");
					flag = false;
					return false;
				}
				if(content==""|| content== null || content=="undifined") {
					layer.msg("请输入内容！");
					flag = false;
					return false;
				}
				if(readCount==""|| readCount == null || readCount=="undifined") {
					readCount = 0;
				}
				content = image_change(content);
				if(flag) {
					$.ajax({
						type : "post",
						url : "${base}/sys/noticeActive/save",
						data : {
							id : id,
							type : type,
							title:title,
							source : source,
							readCount : readCount,
							content : content,
							state : state,
							picUrl : picUrl
							},
						dataType : "json",
						async : false,
						success : function(data) {
							if(data.message == 2) {
								layer.alert('请完善数据');   
									// return false;
								} else if(data.message == 1) {
									layer.msg('保存成功！', {
									  icon: 1,
									  time: 2000 //2秒关闭（如果不配置，默认是3秒）
									}, function(){
										window.location.href="${base}/sys/noticeActive/show";
									});   
								} else {
									layer.msg('系统繁忙！'); 
								}
						}
					}); 
				}
	});
  
  <#if NoticeDTO?? && NoticeDTO.picUrlList??>
  var fileNumber=${NoticeDTO.picUrlList?size+1}
  <#else>
  var fileNumber=1;
  </#if>
  layui.use('upload', function(){
	  var upload = layui.upload;
	  
	  if(fileNumber<10) {
		var uploadInst = upload.render({
		    elem: '#test' //绑定元素
		    ,url: '${base}/uploadImage' //上传接口
		    ,done: function(res){
		    if(res != "") {
	    		var obj = res;
				$("#iconUrl").val('${picUrlHost}' +obj.imageUrl);
				$("#site-demo-upload").prepend("<img id='LAY_demo_upload_" + fileNumber + "' name='LAY_demo_upload' onclick='removeThis(id);' src='"+ '${picUrlHost}'+ obj.imageUrl +"' style='max-width:200px;max-height:200px;margin-left: 5px;'>")
				fileNumber++;
			}
		      //上传完毕回调
		    }
		    ,error: function(){
		      //请求异常回调
		    }
		  });
	  } else {
		  layer.msg('请上传不超过9张图片'); 
	  }

	  
 	});  

	});  
	
	function image_change(pageContents){
		  var imgArray = getExecStrs(pageContents);
		  if(!imgArray && imgArray.length) {
		  console.log(imgArray);
		  $.ajax({
				type : "post",
				contentType : "application/json",
	         	dataType : 'json',
				url : "${base}/uploadBase64Image",
				data : JSON.stringify(imgArray),
				async : false,
				success : function(data) {
					console.log(data);
					if(data.code==1) {
						var imgUrl =data.data;
						for(var i in imgArray) {
							pageContents = pageContents.replace(imgArray[i], imgUrl[i].imageUrl);
						}
						console.log(pageContents)
					}
				}
			}); 
		  }
		return pageContents;
		}
	function getExecStrs(content) {
		var data = [];
		var str = [];
		content.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/g, function (match, capture) {
			if(capture.indexOf("image") != -1 && capture.indexOf("base64") != -1) {
			   data.push(capture);
			   str.push(match);
			}
		});
		console.log(data);
		return data;
	}
</script>
</body>
</html>
